<?php
namespace app\index\library\douyin;

use fast\Http;
use think\Cache;
use think\Db;

class MiniApp
{
    public function getAccessToken($appid,$appsecret,$key = 'douyin')
    {
        $key .= $key.$appid."_acctocken";
        //tocken缓存
        if (Cache::store('redis')->has($key)){
            $access_token = Cache::store('redis')->get($key);
        }else{
            $params = [
                'grant_type'  => 'client_credential',
                'client_key'       => $appid,
                'client_secret'      => $appsecret
            ];

            $options = [
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/json"
                ]
            ];

            $params = json_encode($params);
            $result = Http::sendRequest("https://open.douyin.com/oauth/client_token/", $params, 'POST',$options);
            if (!$result['ret']){
                return "error 001";
            }

            $jsoninfo = (array)json_decode($result['msg'], true);
            $access_token = $jsoninfo['data']['access_token']??'';
            Cache::store('redis')->set($key,$access_token,7000);
        }

        return  $access_token;
    }
}